package cn.tedu.coolshark.controller;

import cn.tedu.coolshark.mapper.UserMapper;
import cn.tedu.coolshark.pojo.dto.UserDto;
import cn.tedu.coolshark.pojo.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@RestController
public class UserController {
    @Autowired
    UserMapper mapper;
    @RequestMapping("/login")
    public int login(@RequestBody UserDto userDto,
                     HttpServletResponse response, HttpSession session) {
        UserVo user = mapper.selectByUsername(userDto.getUsername());
        if (user != null) {
            if (user.getPassword().equals(userDto.getPassword())) {
               //判断是否需要记住用户名和密码
                if (userDto.getRem()){
                    //创建出Cookie对象把用户名和密码装进去
                    Cookie c1 = new Cookie("username",userDto.getUsername());
                    Cookie c2 = new Cookie("password",userDto.getPassword());
                    c1.setMaxAge(60*60*24*30);//设置保存时长
                    //把Cookie响应给客户端
                    response.addCookie(c1);
                    response.addCookie(c2);
                }
                //把当前登录成功的UserVO保存到Session里面
                session.setAttribute("user",user);
                return 1;
            }
            return 2;
        }
        return 3;
    }
    @RequestMapping("/currentUser")
    public UserVo currentUser(HttpSession session){
        return (UserVo) session.getAttribute("user");
    }
    @RequestMapping("/logout")
    public void logout(HttpSession session){
        session.removeAttribute("user");
    }

}
